<template>
    <el-container>
        <el-header height="80px" style="padding: 10px;">
            <!-- 工具/搜索栏 -->
            <div style="padding: 5px; background: #F2F6FC; border-radius: 5px;">
                <div class="topbar">
                    <div class="left-panel">
                        <el-button type="text" style="color: #909399; font-size: 14px;" icon="el-icon-back" @click="back()">返回</el-button> &nbsp;&nbsp;&nbsp;&nbsp;
                        <el-tag type="success" effect="dark" size="large">当前应用：{{ appId }}</el-tag>
                    </div>
                    <div class="right-panel">
                        <div class="right-panel-search">
                            <el-select v-model="refreshInterval" style="width: 120px;">
                                <el-option label="5s刷新一次" :value="5"></el-option>
                                <el-option label="10s刷新一次" :value="10"></el-option>
                                <el-option label="30s刷新一次" :value="30"></el-option>
                                <el-option label="60s刷新一次" :value="60"></el-option>
                            </el-select>
                            <el-select v-model="searchForm.status" placeholder="请选择状态" style="width: 130px;" clearable>
                                <el-option label="在线" :value="true"></el-option>
                                <el-option label="已下线" :value="false"></el-option>
                            </el-select>
                            <el-input v-model="searchForm.searchText" placeholder="搜索关键词..." style="width: 200px;"></el-input>
                            <el-button type="primary" icon="el-icon-search" @click="getInstances()"></el-button>
                            <el-button type="warning" icon="el-icon-refresh" @click="refresh"></el-button>
                        </div>
                    </div>
                </div>
            </div>       
        </el-header>

        <el-main style="padding-left: 10px; padding-right: 10px;">
            <el-card shadow="always" body-style="padding: 0px; min-height: 500px;">
                <el-table
                ref="Table"
                :data="list"
                element-loading-text="加载数据中"
                v-loading="loading"
                :header-row-style="{height:45+'px'}"
                :row-style="{height:60+'px'}"
                style="width: 100%; min-height: 450px;"
                :header-cell-style="{background:'#F2F6FC'}">
                    <el-table-column prop="instanceId"          label="实例ID" sortable></el-table-column>
                    <el-table-column prop="ipAddr"  label="IP地址" ></el-table-column>
                    <el-table-column prop="port"     label="端口号" sortable ></el-table-column>
                    <el-table-column prop="status"   label="状态" sortable>
                        <template slot-scope="scope">
                            <el-button
                                type="text"
                                style="color: #909399"
                                icon="el-icon-loading"
                                v-if="scope.row.statusChanging">{{ scope.row.status?'正在下线中...':'正在上线中...' }}</el-button>
                            <span v-else>
                                <el-tag type="success" v-if="scope.row.status">在线</el-tag>
                                <el-tag type="danger" v-else>已下线</el-tag>
                            </span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="lastUpdatedTimestamp"  label="最后更新时间" ></el-table-column>
                    <el-table-column label="操作" width="200">
                        <template slot-scope="scope">
                            <el-button
                                type="text"
                                style="color: #67C23A"
                                icon="el-icon-view"
                                @click="views(scope.$index, scope.row)">查看</el-button>
                            <el-button
                                type="text"
                                style="color: #F56C6C"
                                icon="el-icon-video-pause"
                                @click="upOrDownInstance(scope.$index, scope.row)" v-if="!scope.row.statusChanging && scope.row.status">下线</el-button>   
                            <el-button
                                type="text"
                                style="color: #409EFF"
                                icon="el-icon-video-play"
                                @click="upOrDownInstance(scope.$index, scope.row)" v-if="!scope.row.statusChanging && !scope.row.status">上线</el-button>
                        </template>
                    </el-table-column>
                    <template #empty>
                        <el-empty :description="'查无数据'" :image-size="100"></el-empty>
                    </template>
                </el-table>
            </el-card>
            
        </el-main>

        <el-dialog 
            :title="currentRow.instanceId" 
            :visible.sync="visibleViewsDialog"
            v-if="visibleViewsDialog"
            width="600px"
            :show-close="true"
            @close="closeViews()"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            append-to-body>
                        
            <el-descriptions  :column="1">
                <el-descriptions-item label="主机名">{{ currentRow.hostName }}</el-descriptions-item>
                <el-descriptions-item label="IP地址">{{ currentRow.ipAddr }}</el-descriptions-item>
                <el-descriptions-item label="端口号">{{ currentRow.port }}</el-descriptions-item>
                <el-descriptions-item label="状态">{{ currentRow.status?'在线':'已下线' }}</el-descriptions-item>
                <el-descriptions-item label="元数据">
                    <table style="width: 100%;">
                        <thead style="background: #F2F6FC; line-height: 25px;">
                            <tr>
                                <th style="width: 40%;">元数据键</th>
                                <th style="width: 45%;">元数据值</th>
                                <th style="width: 15%;"></th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="(mkey, index) in Object.keys(currentRow.metadata)" :key="index">
                                <td>{{ mkey }}</td>
                                <td>{{ Object.values(currentRow.metadata)[index] }}</td>
                                <td><el-button type="text" @click="update(mkey, Object.values(currentRow.metadata)[index])">编辑</el-button></td>
                            </tr>
                            <tr>
                                <td colspan="3" style="text-align: center;"> 
                                    <el-button type="text" style="color: #67C23A;" @click="open()">添加标签</el-button>
                                    <el-button type="text" style="color: #E6A23C;" @click="submit()">保存变更</el-button>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </el-descriptions-item>
                <el-descriptions-item label="最后更新时间">{{ currentRow.lastUpdatedTimestamp }}</el-descriptions-item>
            </el-descriptions>

        </el-dialog>

        <add-update-metadata ref="AddUpdateMetadata" @success="success"></add-update-metadata>


    </el-container>
</template>

<script>
import addUpdateMetadata from './modules/add_update_metadata.vue'

export default {
    components: {
        addUpdateMetadata
    },
    data() {
        return {
            appId: '',
            searchForm: {
                appId: null,
                searchText: '',
                status: null
            },
            list: [],
            loading: false,
            visibleViewsDialog: false,
            currentRow: {},
            timer: null,
            refreshInterval: 10
        }
    },
    mounted() {       
        // 初始化列表
        const appId = this.$route.query.appId
        if (appId != null) {
            this.appId = appId;
            this.searchForm.appId = appId;
        }
        this.getInstances()
        this.setTimer()
    },
    beforeDestroy() {
        this.clearTimer()
    },
    methods: {
        /**
         * @title 获取列表
         */
        async getInstances() {
            this.loading = true
            let response = await this.$API.regcenter.getInstances(this.searchForm)   
            this.list = response.data
            this.loading = false         
        },

        refresh() {
            this.searchForm.searchText = ''
            this.getInstances()
        },

        setTimer() {
            this.clearTimer()
            let that = this
            this.timer = setInterval(() => {
                that.getInstances()                
            }, 10000)
        },

        clearTimer() {
            clearInterval(this.timer)
            this.timer = null
        },

        views(index, row) {
            this.visibleViewsDialog = true
            this.currentRow = row
        },

        closeViews() {
            this.visibleViewsDialog = false
            this.currentRow = {}
        },

        open() {
            this.$nextTick(() => {
                this.$refs.AddUpdateMetadata.open(
                    {'mkey': null, 'mvalue': null}
                ) 
            })   
        },

        update(mkey, mvalue) {
            this.$nextTick(() => {
                this.$refs.AddUpdateMetadata.open(
                    {'mkey': mkey, 'mvalue': mvalue}
                ) 
            })  
        },

        success(data) {
            if (data != null && data != 'Undefined') {
                const m = JSON.parse(data);
                this.$set(this.currentRow.metadata, m.mkey, m.mvalue)    
            }
        },

        async submit() {
            let data = {
                'appId': this.currentRow.appId,
                'instanceId': this.currentRow.instanceId,
                'metadata': this.currentRow.metadata
            }
            let response = await this.$API.regcenter.modifyMetadata(data)
            this.$message.success(response.message)
        },

        upOrDownInstance(index, row) {

            let opMsg = "确定将该应用实例 [" + row.instanceId + '] ' +(row.status?'下线':'上线')+'吗?'
            this.$confirm(opMsg, row.status?'下线提示':'上线提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                center: true
            }).then(() => {
                
                let data = {
                    'appId': row.appId,
                    'instanceId': row.instanceId,
                    'status': !row.status
                }

                this.$API.regcenter.modifyStatus(data).then(response => {
                    this.$message.success(response.message)
                    this.getInstances()
                })

            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消操作'
                })
            })
        },

        back() {
            this.$router.back(-1)
        },
       
    }
}
</script>

<style lang="scss" scoped>
.el-main {
    width: 100%;
    height: 100%;
    padding: 0px;
}
.topbar {
    height: 50px; 
    display: flex;
    justify-content:space-between;
    margin-bottom: 0px;

    .left-panel {
        display: flex;
        align-items: center;
    }
    .right-panel {
        display: flex;
        align-items: center;
    }

    .right-panel-search {display: flex;align-items: center;}

    .right-panel-search > * + * {margin-left:10px;}
}


</style>